import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:just_audio/just_audio.dart';
import 'dart:io';

enum DialogType {
  confirm,
}

class CustomDialog extends StatelessWidget {
  const CustomDialog({
    Key? key,
    this.title,
    this.url,
    this.content,
    this.rightText,
    this.leftText,
    this.onTapLeft,
    this.onTapRight,
  }) : super(key: key);
  final String? title;
  final String? url;
  final String? content;
  final String? rightText;
  final String? leftText;
  final Function()? onTapLeft;
  final Function()? onTapRight;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: Container(
            width: 280.w,
            color: Styles.c_FFFFFF,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: EdgeInsets.symmetric(
                    horizontal: 20.w,
                    vertical: 20.h,
                  ),
                  child: Text(
                    title ?? '',
                    style: Styles.ts_0C1C33_17sp,
                  ),
                ),
                Divider(
                  color: Styles.c_E8EAEF,
                  height: 0.5.h,
                ),
                Row(
                  children: [
                    _button(
                      bgColor: Styles.c_FFFFFF,
                      text: leftText ?? StrRes.cancel,
                      textStyle: Styles.ts_0C1C33_17sp,
                      onTap: onTapLeft ?? () => Get.back(result: false),
                    ),
                    Container(
                      color: Styles.c_E8EAEF,
                      width: 0.5.w,
                      height: 48.h,
                    ),
                    _button(
                      bgColor: Styles.c_FFFFFF,
                      text: rightText ?? StrRes.determine,
                      textStyle: Styles.ts_0089FF_17sp,
                      onTap: onTapRight ?? () => Get.back(result: true),
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _button({
    required Color bgColor,
    required String text,
    required TextStyle textStyle,
    Function()? onTap,
  }) =>
      Expanded(
        child: GestureDetector(
          onTap: onTap,
          child: Container(
            decoration: BoxDecoration(
              color: bgColor,
            ),
            height: 48.h,
            alignment: Alignment.center,
            child: Text(
              text,
              style: textStyle,
            ),
          ),
        ),
      );
}

class ForwardHintDialog extends StatefulWidget {
  const ForwardHintDialog({
    Key? key,
    required this.title,
    this.checkedList = const [],
    this.messages = const [],
  }) : super(key: key);
  final String title;
  final List<dynamic> checkedList;
  final List<Message> messages;
  @override
  State<ForwardHintDialog> createState() => _ForwardHintDialogState();
  
}

class _ForwardHintDialogState extends State<ForwardHintDialog> {
  @override
  Widget build(BuildContext context) {
    final list = IMUtils.convertCheckedListToForwardObj(widget.checkedList);
    final screenHeight = MediaQuery.of(context).size.height;
    
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: SingleChildScrollView(
          child: Container(
            constraints: BoxConstraints(
              maxHeight: screenHeight * 0.8,
              maxWidth: MediaQuery.of(context).size.width - 72.w,
            ),
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
            margin: EdgeInsets.symmetric(horizontal: 36.w),
            decoration: BoxDecoration(
              color: Styles.c_FFFFFF,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                (list.length == 1 ? StrRes.sentTo : StrRes.sentSeparatelyTo).toText
                  ..style = Styles.ts_0C1C33_17sp_medium,
                5.verticalSpace,
                list.length == 1
                    ? Row(
                        children: [
                          AvatarView(
                            url: list.first['faceURL'],
                            text: list.first['nickname'],
                          ),
                          10.horizontalSpace,
                          Expanded(
                            child: (list.first['nickname'] ?? '').toText
                              ..style = Styles.ts_0C1C33_17sp
                              ..maxLines = 1
                              ..overflow = TextOverflow.ellipsis,
                          ),
                        ],
                      )
                    : ConstrainedBox(
                        constraints: BoxConstraints(maxHeight: 120.h),
                        child: GridView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 5,
                            crossAxisSpacing: 10.w,
                            mainAxisSpacing: 10.h,
                            childAspectRatio: 50.w / 70.h,
                          ),
                          itemCount: list.length,
                          shrinkWrap: true,
                          itemBuilder: (_, index) => Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              AvatarView(
                                url: list.elementAt(index)['faceURL'],
                                text: list.elementAt(index)['nickname'],
                              ),
                              4.verticalSpace,
                              Expanded(
                                child: (list.elementAt(index)['nickname'] ?? '').toText
                                  ..style = Styles.ts_8E9AB0_10sp
                                  ..maxLines = 1
                                  ..overflow = TextOverflow.ellipsis
                                  ..textAlign = TextAlign.center,
                              ),
                            ],
                          ),
                        ),
                      ),
                5.verticalSpace,
                widget.title.toText
                  ..style = Styles.ts_8E9AB0_14sp
                  ..maxLines = 1
                  ..overflow = TextOverflow.ellipsis,
                // 根据消息数量决定显示方式
                if (widget.messages.isNotEmpty) ...[
                  12.verticalSpace,
                  // 单个消息：直接显示内容
                  if (widget.messages.length == 1) 
                    _buildSingleMessagePreview(widget.messages.first)
                  // 多个消息：显示查看详情按钮
                  else
                    GestureDetector(
                      onTap: () {
                        _showMessageDetailsBottomSheet();
                      },
                      child: Row(
                        children: [
                          Icon(
                            Icons.keyboard_arrow_up,
                            size: 16.w,
                            color: Styles.c_0089FF,
                          ),
                          4.horizontalSpace,
                          '查看详情'.toText
                            ..style = Styles.ts_0089FF_14sp,
                        ],
                      ),
                    ),
                ],
                16.verticalSpace,
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    StrRes.cancel.toText
                      ..style = Styles.ts_0C1C33_17sp
                      ..onTap = () => Get.back(),
                    26.horizontalSpace,
                    StrRes.determine.toText
                      ..style = Styles.ts_0089FF_17sp
                      ..onTap = () => Get.back(result: true),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  // 构建单个消息预览
  Widget _buildSingleMessagePreview(Message message) {
    return GestureDetector(
      onTap: () => _handleMessageTap(message),
      child: Container(
        padding: EdgeInsets.all(12.w),
        decoration: BoxDecoration(
          color: Styles.c_F8F9FA,
          borderRadius: BorderRadius.circular(8.r),
          border: Border.all(
            color: Styles.c_E8EAEF,
            width: 1,
          ),
        ),
        child: _buildMessageContent(message),
      ),
    );
  }
  
  // 处理消息点击事件
  void _handleMessageTap(Message message) {
    switch (message.contentType) {
      case MessageType.picture:
        // 预览图片
        IMUtils.previewPicture(message, allList: widget.messages);
        break;
      case MessageType.video:
        // 播放视频
        IMUtils.previewMediaFile(
          context: context,
          message: message,
        );
        break;
      case MessageType.voice:
        // 播放语音
        _playVoice(message);
        break;
      default:
        // 其他类型消息暂不处理
        break;
    }
  }
  
  void _playVoice(Message message) async {
    final soundPath = message.soundElem?.soundPath;
    final sourceUrl = message.soundElem?.sourceUrl;
    final player = AudioPlayer();

    try {
      if (soundPath != null && File(soundPath).existsSync()) {
        await player.setFilePath(soundPath);
      } else if (sourceUrl != null && sourceUrl.isNotEmpty) {
        await player.setUrl(sourceUrl);
      } else {
        IMViews.showToast('语音资源不可用');
        player.dispose();
        return;
      }

      await player.play();

      // 播放完成后释放资源
      player.playerStateStream.listen((state) {
        if (state.processingState == ProcessingState.completed) {
          player.dispose();
        }
      });
    } catch (e) {
      IMViews.showToast('播放失败');
      player.dispose();
    }
  }
  
  // // 构建图片缩略图
  // Widget _buildPictureThumbnail(Message message) {
  //   final pictureElem = message.pictureElem;
  //   final thumbnailUrl = pictureElem?.snapshotPicture?.url;
    
  //   return Container(
  //     width: 40.w,
  //     height: 40.w,
  //     decoration: BoxDecoration(
  //       borderRadius: BorderRadius.circular(6.r),
  //       color: Styles.c_F0F2F6,
  //     ),
  //     child: ClipRRect(
  //       borderRadius: BorderRadius.circular(6.r),
  //       child: thumbnailUrl?.isNotEmpty == true
  //           ? ImageUtil.networkImage(
  //               url: thumbnailUrl!,
  //               width: 40.w,
  //               height: 40.w,
  //               fit: BoxFit.cover,
  //               errorWidget: Icon(
  //                 Icons.image,
  //                 size: 20.w,
  //                 color: Styles.c_8E9AB0,
  //               ),
  //             )
  //           : Icon(
  //               Icons.image,
  //               size: 20.w,
  //               color: Styles.c_8E9AB0,
  //             ),
  //     ),
  //   );
  // }

  // // 构建视频缩略图
  // Widget _buildVideoThumbnail(Message message) {
  //   final videoElem = message.videoElem;
  //   final thumbnailUrl = videoElem?.snapshotUrl;
    
  //   return Container(
  //     width: 40.w,
  //     height: 40.w,
  //     decoration: BoxDecoration(
  //       borderRadius: BorderRadius.circular(6.r),
  //       color: Styles.c_F0F2F6,
  //     ),
  //     child: Stack(
  //       children: [
  //         ClipRRect(
  //           borderRadius: BorderRadius.circular(6.r),
  //           child: thumbnailUrl?.isNotEmpty == true
  //               ? ImageUtil.networkImage(
  //                   url: thumbnailUrl!,
  //                   width: 40.w,
  //                   height: 40.w,
  //                   fit: BoxFit.cover,
  //                   errorWidget: Icon(
  //                     Icons.videocam,
  //                     size: 20.w,
  //                     color: Styles.c_8E9AB0,
  //                   ),
  //                 )
  //               : Icon(
  //                   Icons.videocam,
  //                   size: 20.w,
  //                   color: Styles.c_8E9AB0,
  //                 ),
  //         ),
  //         // 播放按钮覆盖层
  //         Positioned.fill(
  //           child: Container(
  //             decoration: BoxDecoration(
  //               borderRadius: BorderRadius.circular(6.r),
  //               color: Colors.black.withOpacity(0.3),
  //             ),
  //             child: Icon(
  //               Icons.play_arrow,
  //               color: Colors.white,
  //               size: 16.w,
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  // // 格式化视频时长
  // String _formatDuration(int seconds) {
  //   final minutes = seconds ~/ 60;
  //   final remainingSeconds = seconds % 60;
  //   return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  // }
  
  void _showMessageDetailsBottomSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => MessageDetailsBottomSheet(messages: widget.messages),
    );
  }
  
  // 构建消息内容预览
  Widget _buildMessageContent(Message message) {
    switch (message.contentType) {
      case MessageType.text:
        return Row(
          children: [
            Icon(
              Icons.chat_bubble_outline,
              size: 16.w,
              color: Styles.c_0089FF,
            ),
            8.horizontalSpace,
            Expanded(
              child: Text(
                message.textElem?.content ?? '',
                style: Styles.ts_0C1C33_14sp,
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        );
        
      case MessageType.picture:
        return GestureDetector(
          onTap: () => _handleMessageTap(message),
          child: Row(
            children: [
              _buildPictureThumbnail(message),
              8.horizontalSpace,
              Text(
                '[图片]',
                style: Styles.ts_0C1C33_14sp,
              ),
            ],
          ),
        );
        
      case MessageType.video:
        return GestureDetector(
          onTap: () => _handleMessageTap(message),
          child: Row(
            children: [
              _buildVideoThumbnail(message),
              8.horizontalSpace,
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '[视频]',
                    style: Styles.ts_0C1C33_14sp,
                  ),
                  if (message.videoElem?.duration != null)
                    Text(
                      _formatDuration(message.videoElem!.duration!),
                      style: Styles.ts_8E9AB0_12sp,
                    ),
                ],
              ),
            ],
          ),
        );
        
      case MessageType.voice:
        return GestureDetector(
          onTap: () => _handleMessageTap(message),
          child: Row(
            children: [
              Icon(
                Icons.keyboard_voice,
                size: 16.w,
                color: Styles.c_0089FF,
              ),
              8.horizontalSpace,
              Text(
                '[语音] ${message.soundElem?.duration ?? 0}"',
                style: Styles.ts_0C1C33_14sp,
              ),
            ],
          ),
        );
        
      case MessageType.file:
        return Row(
          children: [
            Icon(
              Icons.insert_drive_file,
              size: 16.w,
              color: Styles.c_0089FF,
            ),
            8.horizontalSpace,
            Expanded(
              child: Text(
                message.fileElem?.fileName ?? '[文件]',
                style: Styles.ts_0C1C33_14sp,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        );
        
      case MessageType.location:
        return Row(
          children: [
            Icon(
              Icons.location_on,
              size: 16.w,
              color: Styles.c_0089FF,
            ),
            8.horizontalSpace,
            Text(
              '[位置]',
              style: Styles.ts_0C1C33_14sp,
            ),
          ],
        );
        
      case MessageType.card:
        return Row(
          children: [
            Icon(
              Icons.person,
              size: 16.w,
              color: Styles.c_0089FF,
            ),
            8.horizontalSpace,
            Text(
              '[名片]',
              style: Styles.ts_0C1C33_14sp,
            ),
          ],
        );
        
      case MessageType.atText:
        return Row(
          children: [
            Icon(
              Icons.alternate_email,
              size: 16.w,
              color: Styles.c_0089FF,
            ),
            8.horizontalSpace,
            Expanded(
              child: Text(
                message.atTextElem?.text ?? '',
                style: Styles.ts_0C1C33_14sp,
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        );
        
      default:
        return Row(
          children: [
            Icon(
              Icons.help_outline,
              size: 16.w,
              color: Styles.c_8E9AB0,
            ),
            8.horizontalSpace,
            Text(
              '[未知消息类型]',
              style: Styles.ts_0C1C33_14sp,
            ),
          ],
        );
    }
  }
  
  // 构建图片缩略图
  Widget _buildPictureThumbnail(Message message) {
    final pictureElem = message.pictureElem;
    final thumbnailUrl = pictureElem?.snapshotPicture?.url;
    
    return Container(
      width: 40.w,
      height: 40.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: Styles.c_F0F2F6,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(6.r),
        child: thumbnailUrl?.isNotEmpty == true
            ? ImageUtil.networkImage(
                url: thumbnailUrl!,
                width: 40.w,
                height: 40.w,
                fit: BoxFit.cover,
                errorWidget: Icon(
                  Icons.image,
                  size: 20.w,
                  color: Styles.c_8E9AB0,
                ),
              )
            : Icon(
                Icons.image,
                size: 20.w,
                color: Styles.c_8E9AB0,
              ),
      ),
    );
  }

  // 构建视频缩略图
  Widget _buildVideoThumbnail(Message message) {
    final videoElem = message.videoElem;
    final thumbnailUrl = videoElem?.snapshotUrl;
    
    return Container(
      width: 40.w,
      height: 40.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: Styles.c_F0F2F6,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(6.r),
            child: thumbnailUrl?.isNotEmpty == true
                ? ImageUtil.networkImage(
                    url: thumbnailUrl!,
                    width: 40.w,
                    height: 40.w,
                    fit: BoxFit.cover,
                    errorWidget: Icon(
                      Icons.videocam,
                      size: 20.w,
                      color: Styles.c_8E9AB0,
                    ),
                  )
                : Icon(
                    Icons.videocam,
                    size: 20.w,
                    color: Styles.c_8E9AB0,
                  ),
          ),
          // 播放按钮覆盖层
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.r),
                color: Colors.black.withOpacity(0.3),
              ),
              child: Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 16.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 格式化视频时长
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }
}

// 新增：消息详情底部弹出页面
class MessageDetailsBottomSheet extends StatelessWidget {
  final List<Message> messages;
  
  const MessageDetailsBottomSheet({
    Key? key,
    required this.messages,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.8,
      decoration: BoxDecoration(
        color: Styles.c_FFFFFF,
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.r)),
      ),
      child: Column(
        children: [
          // 顶部拖拽条和标题
          Container(
            padding: EdgeInsets.symmetric(vertical: 12.h),
            child: Column(
              children: [
                Container(
                  width: 36.w,
                  height: 4.h,
                  decoration: BoxDecoration(
                    color: Styles.c_E8EAEF,
                    borderRadius: BorderRadius.circular(2.r),
                  ),
                ),
                16.verticalSpace,
                Row(
                  children: [
                    16.horizontalSpace,
                    Expanded(
                      child: Text(
                        '转发消息详情 (${messages.length}条)',
                        style: Styles.ts_0C1C33_17sp_medium,
                        textAlign: TextAlign.center,
                      ),
                    ),
                    GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        padding: EdgeInsets.all(8.w),
                        child: Icon(
                          Icons.close,
                          size: 20.w,
                          color: Styles.c_8E9AB0,
                        ),
                      ),
                    ),
                    8.horizontalSpace,
                  ],
                ),
              ],
            ),
          ),
          
          // 分割线
          Container(
            height: 1.h,
            color: Styles.c_E8EAEF,
          ),
          
          // 消息列表
          Expanded(
            child: ListView.separated(
              padding: EdgeInsets.symmetric(vertical: 8.h),
              itemCount: messages.length,
              separatorBuilder: (_, __) => Container(
                height: 1.h,
                color: Styles.c_F8F9FA,
                margin: EdgeInsets.symmetric(horizontal: 16.w),
              ),
              itemBuilder: (context, index) {
                final message = messages[index];
                return _buildMessageItem(message);
              },
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildMessageItem(Message message) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      child: _buildBottomSheetMessageContent(message),
    );
  }
  
  Widget _buildBottomSheetMessageContent(Message message) {
    switch (message.contentType) {
      case MessageType.text:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Text(
            message.textElem?.content ?? '',
            style: Styles.ts_0C1C33_14sp,
          ),
        );
        
      case MessageType.picture:
         return GestureDetector(
          onTap: () {
            IMUtils.previewPicture(message, allList: messages);
          },
          child: Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: Styles.c_F8F9FA,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 图片缩略图
                _buildPictureThumbnail(message),
                8.horizontalSpace,
                Text(
                  '[图片]',
                  style: Styles.ts_0C1C33_14sp,
                ),
              ],
            ),
          ),
        );
        
      case MessageType.video:
         return GestureDetector(
          onTap: () {
           // 使用支持视频播放的预览
            IMUtils.previewMediaFile(
              context: Get.context!,
              message: message,
            );
          },
          child: Container(
            padding: EdgeInsets.all(8.w),
            decoration: BoxDecoration(
              color: Styles.c_F8F9FA,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 视频缩略图
                _buildVideoThumbnail(message),
                8.horizontalSpace,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '[视频]',
                      style: Styles.ts_0C1C33_14sp,
                    ),
                    if (message.videoElem?.duration != null)
                      Text(
                        _formatDuration(message.videoElem!.duration!),
                        style: Styles.ts_8E9AB0_12sp,
                      ),
                  ],
                ),
              ],
            ),
          ),
        );  
      case MessageType.voice:
       return GestureDetector(
          onTap: () => _playVoice(message),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
            decoration: BoxDecoration(
              color: Styles.c_F8F9FA,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.keyboard_voice,
                  size: 18.w,
                  color: Colors.blue,
                ),
                8.horizontalSpace,
                Text(
                  '[语音] ${message.soundElem?.duration ?? 0}"',
                  style: Styles.ts_0C1C33_14sp,
                ),
              ],
            ),
          ),
        );
        
      case MessageType.file:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.insert_drive_file,
                size: 18.w,
                color: Colors.orange,
              ),
              8.horizontalSpace,
              Expanded(
                child: Text(
                  message.fileElem?.fileName ?? '[文件]',
                  style: Styles.ts_0C1C33_14sp,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        );
        
      case MessageType.location:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.location_on,
                size: 18.w,
                color: Colors.redAccent,
              ),
              8.horizontalSpace,
              Text(
                '[位置]',
                style: Styles.ts_0C1C33_14sp,
              ),
            ],
          ),
        );
        
      case MessageType.card:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.person,
                size: 18.w,
                color: Colors.brown,
              ),
              8.horizontalSpace,
              Text(
                '[名片]',
                style: Styles.ts_0C1C33_14sp,
              ),
            ],
          ),
        );
        
      case MessageType.atText:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Text(
            message.atTextElem?.text ?? '',
            style: Styles.ts_0C1C33_14sp,
          ),
        );
        
      default:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Styles.c_F8F9FA,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.help_outline,
                size: 18.w,
                color: Styles.c_8E9AB0,
              ),
              8.horizontalSpace,
              Text(
                '[未知消息类型]',
                style: Styles.ts_0C1C33_14sp,
              ),
            ],
          ),
        );
    }
  }

    void _playVoice(Message message) async {
    final soundPath = message.soundElem?.soundPath;
    final sourceUrl = message.soundElem?.sourceUrl;
    final player = AudioPlayer();

    try {
      if (soundPath != null && File(soundPath).existsSync()) {
        await player.setFilePath(soundPath);
      } else if (sourceUrl != null && sourceUrl.isNotEmpty) {
        await player.setUrl(sourceUrl);
      } else {
        IMViews.showToast('语音资源不可用');
        player.dispose();
        return;
      }

      await player.play();

      // 播放完成后释放资源
      player.playerStateStream.listen((state) {
        if (state.processingState == ProcessingState.completed) {
          player.dispose();
        }
      });
    } catch (e) {
      IMViews.showToast('播放失败');
      player.dispose();
    }
  }
    // 构建图片缩略图
  Widget _buildPictureThumbnail(Message message) {
    final pictureElem = message.pictureElem;
    final thumbnailUrl = pictureElem?.snapshotPicture?.url;
    
    return Container(
      width: 60.w,
      height: 60.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: Styles.c_F0F2F6,
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(6.r),
        child: thumbnailUrl?.isNotEmpty == true
            ? ImageUtil.networkImage(
                url: thumbnailUrl!,
                width: 60.w,
                height: 60.w,
                fit: BoxFit.cover,
                errorWidget: Icon(
                  Icons.image,
                  size: 30.w,
                  color: Styles.c_8E9AB0,
                ),
              )
            : Icon(
                Icons.image,
                size: 30.w,
                color: Styles.c_8E9AB0,
              ),
      ),
    );
  }

  // 构建视频缩略图
  Widget _buildVideoThumbnail(Message message) {
    final videoElem = message.videoElem;
    final thumbnailUrl = videoElem?.snapshotUrl;
    
    return Container(
      width: 60.w,
      height: 60.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6.r),
        color: Styles.c_F0F2F6,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(6.r),
            child: thumbnailUrl?.isNotEmpty == true
                ? ImageUtil.networkImage(
                    url: thumbnailUrl!,
                    width: 60.w,
                    height: 60.w,
                    fit: BoxFit.cover,
                    errorWidget: Icon(
                      Icons.videocam,
                      size: 30.w,
                      color: Styles.c_8E9AB0,
                    ),
                  )
                : Icon(
                    Icons.videocam,
                    size: 30.w,
                    color: Styles.c_8E9AB0,
                  ),
          ),
          // 播放按钮覆盖层
          Positioned.fill(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.r),
                color: Colors.black.withOpacity(0.3),
              ),
              child: Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 24.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 格式化视频时长
  String _formatDuration(int seconds) {
    final minutes = seconds ~/ 60;
    final remainingSeconds = seconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${remainingSeconds.toString().padLeft(2, '0')}';
  }
}


// 专门用于转发名片消息的对话框
class ForwardCardDialog extends StatelessWidget {
  final String title;
  final List<dynamic> checkedList;
  final UserInfo cardUserInfo;

  const ForwardCardDialog({
    Key? key,
    required this.title,
    required this.checkedList,
    required this.cardUserInfo,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final list = IMUtils.convertCheckedListToForwardObj(checkedList);
    final screenHeight = MediaQuery.of(context).size.height;
    
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: SingleChildScrollView(
          child: Container(
            constraints: BoxConstraints(
              maxHeight: screenHeight * 0.8,
              maxWidth: MediaQuery.of(context).size.width - 72.w,
            ),
            padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
            margin: EdgeInsets.symmetric(horizontal: 36.w),
            decoration: BoxDecoration(
              color: Styles.c_FFFFFF,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题
                Row(
                  children: [
                    Icon(
                      Icons.share,
                      size: 20.w,
                      color: Styles.c_0089FF,
                    ),
                    8.horizontalSpace,
                    Text(
                      '推荐名片',
                      style: Styles.ts_0C1C33_17sp_medium,
                    ),
                  ],
                ),
                16.verticalSpace,
                
                // 接收人信息
                Text(
                  list.length == 1 ? '发送给:' : '分别发送给:',
                  style: Styles.ts_8E9AB0_14sp,
                ),
                8.verticalSpace,
                
                list.length == 1
                    ? _buildSingleReceiver(list.first)
                    : _buildMultipleReceivers(list),
                
                20.verticalSpace,
                
                // 名片预览
                Text(
                  '名片预览:',
                  style: Styles.ts_8E9AB0_14sp,
                ),
                12.verticalSpace,
                _buildCardPreview(),
                
                24.verticalSpace,
                
                // 操作按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                      onTap: () => Get.back(),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
                        child: Text(
                          StrRes.cancel,
                          style: Styles.ts_8E9AB0_16sp,
                        ),
                      ),
                    ),
                    16.horizontalSpace,
                    GestureDetector(
                      onTap: () => Get.back(result: true),
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 10.h),
                        decoration: BoxDecoration(
                          color: Styles.c_0089FF,
                          borderRadius: BorderRadius.circular(6.r),
                        ),
                        child: Text(
                          StrRes.determine,
                          style: Styles.ts_FFFFFF_16sp,
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建单个接收人
  Widget _buildSingleReceiver(Map<String, dynamic> receiver) {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Styles.c_F8F9FA,
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        children: [
          AvatarView(
            url: receiver['faceURL'],
            text: receiver['nickname'],
            width: 40.w,
            height: 40.w,
          ),
          12.horizontalSpace,
          Expanded(
            child: Text(
              receiver['nickname'] ?? '未知用户',
              style: Styles.ts_0C1C33_17sp,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  // 构建多个接收人
  Widget _buildMultipleReceivers(List<Map<String, dynamic>> receivers) {
    return Container(
      constraints: BoxConstraints(maxHeight: 120.h),
      child: GridView.builder(
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 8.w,
          mainAxisSpacing: 8.h,
          childAspectRatio: 1.0,
        ),
        itemCount: receivers.length,
        shrinkWrap: true,
        itemBuilder: (_, index) {
          final receiver = receivers[index];
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              AvatarView(
                url: receiver['faceURL'],
                text: receiver['nickname'],
                width: 36.w,
                height: 36.w,
              ),
              4.verticalSpace,
              Expanded(
                child: Text(
                  receiver['nickname'] ?? '未知用户',
                  style: Styles.ts_8E9AB0_10sp,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // 构建名片预览
  Widget _buildCardPreview() {
    return GestureDetector(
      onTap: () {
        // 验证用户信息是否完整
        final userID = cardUserInfo.userID?.trim();
        if (userID == null || userID.isEmpty) {
          IMViews.showToast('名片信息不完整，无法查看用户资料');
          return;
        }
        
        // 返回跳转信息，由调用方处理跳转
        Get.back(result: {
          'action': 'viewUserProfile',
          'userID': userID,
          'nickname': cardUserInfo.nickname,
          'faceURL': cardUserInfo.faceURL,
        });
      },
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Styles.c_E8EAEF, width: 1),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 名片标题
            Row(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Styles.c_0089FF.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.person_pin,
                        size: 16.w,
                        color: Styles.c_0089FF,
                      ),
                      4.horizontalSpace,
                      Text(
                        '个人名片',
                        style: Styles.ts_0089FF_12sp,
                      ),
                    ],
                  ),
                ),
                Spacer(),
                // 添加查看资料提示
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: Styles.c_0089FF.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    '点击查看资料',
                    style: TextStyle(
                      color: Styles.c_0089FF,
                      fontSize: 10.sp,
                    ),
                  ),
                ),
              ],
            ),
            16.verticalSpace,
            
            // 用户信息
            Row(
              children: [
                // 头像
                AvatarView(
                  url: cardUserInfo.faceURL,
                  text: cardUserInfo.nickname ?? cardUserInfo.userID ?? '未知用户',
                  width: 56.w,
                  height: 56.w,
                  borderRadius: BorderRadius.circular(28.r),
                  showDefaultAvatar: true,
                ),
                16.horizontalSpace,
                
                // 用户详细信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 昵称
                      Text(
                        cardUserInfo.nickname ?? '未知用户',
                        style: Styles.ts_0C1C33_17sp_medium,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      
                      if (cardUserInfo.userID?.isNotEmpty == true) ...[
                        6.verticalSpace,
                        Row(
                          children: [
                            Text(
                              'ID: ',
                              style: Styles.ts_8E9AB0_12sp,
                            ),
                            Expanded(
                              child: Text(
                                cardUserInfo.userID!,
                                style: Styles.ts_8E9AB0_12sp,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ],
                      
                      if (cardUserInfo.remark?.isNotEmpty == true) ...[
                        4.verticalSpace,
                        Row(
                          children: [
                            Text(
                              '备注: ',
                              style: Styles.ts_8E9AB0_12sp,
                            ),
                            Expanded(
                              child: Text(
                                cardUserInfo.remark!,
                                style: Styles.ts_8E9AB0_12sp,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}